'use strict';

const path = require('path');
const { Controller } = require('ee-core');
const Log = require('ee-core/log');
const Services = require('ee-core/services');
const CoreElectronWindow = require('ee-core/electron/window');
const CoreElectronApp = require('ee-core/electron/app');
const Ps = require('ee-core/ps');
const Conf = require('ee-core/config')
const { Menu, BrowserWindow, dialog } = require('electron');
const Addon = require('ee-core/addon');

/**
 * HomeController
 * @class
 */
class HomeController extends Controller {

    constructor(ctx) {
        super(ctx);
    }


    /**
     * 打开新窗口
     */
    async openNewWindow (args) {
        const { content, windowName, windowTitle } = args
        let opt = {
            title: windowTitle
        }

        const allWindows = BrowserWindow.getAllWindows();
        for (let i = 0; i < allWindows.length; i++) {
            const window = allWindows[i]
            if(window.getTitle() === windowTitle) {
                dialog.showMessageBox({
                    message: '单据已打开，不允许多开单据'
                })

                return
            }
        }


        let addr = 'http://localhost:8080'
        let contentUrl = null
        if (Ps.isProd()) {
            const mainServer = Conf.getValue('mainServer');
            if (Conf.isFileProtocol(mainServer)) {
                addr = mainServer.protocol + path.join(Ps.getHomeDir(), mainServer.indexPath);
            } else {
                addr = mainServer.protocol + mainServer.host + ':' + mainServer.port;
            }
        }

        contentUrl = addr + content;

        const win = Addon.get('window').create(windowName, opt);
        win.center()
        win.webContents.openDevTools()
        const winContentsId = win.webContents.id;

        await win.loadURL(contentUrl)


        return winContentsId
    }



}

HomeController.toString = () => '[class HomeController]';
module.exports = HomeController;
